package com.bluefish.bltuan.tools;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImageZoom {

	private static final String JPG = "jpg";
	private static final int EIGHTY = 80;
    private File sourceFile;	
    private File destinationFile;	
    private int newWidth = -1;			
    private int newHeight = -1;
    private int defaultNewWidth = EIGHTY;	
    private int defaultNewHeight = EIGHTY;
	private static final Logger LOG = LoggerFactory.getLogger(ImageZoom.class);	
	
	public ImageZoom() {};
	
	public ImageZoom(String sourceFile, String destinationFile) {
		this.sourceFile = new File(sourceFile);
		this.destinationFile = new File(destinationFile);
	}

	public ImageZoom(String sourceFile, String destinationFile, int newWidth, int newHeight) {
		this(sourceFile, destinationFile);
		this.setNw(newWidth);
		this.setNh(newHeight);
	}
	
	public ImageZoom(File sourceFile, File destinationFile, int newWidth, int newHeight) {
		this.sourceFile = sourceFile;
		this.destinationFile = destinationFile;
		this.setNw(newWidth);
		this.setNh(newHeight);
	}
	
	public ImageZoom(String sourceFile, String destinationFile, int newWidth, int newHeight,
	        int defaultNewWidth, int defaultNewHeight) {
		this(sourceFile, destinationFile, newWidth, newHeight);
		this.setDefaultNw(defaultNewWidth);
		this.setDefaultNh(defaultNewHeight);
	}
	
	private void setNw (int newWidth) {
		if (newWidth == -1) {
			this.newWidth = this.defaultNewWidth;
		} else {
			this.newWidth = newWidth;
		}
	}
	
	private void setNh (int newHeight) {
	
		if (newHeight == -1) {
		
			this.newHeight = this.defaultNewHeight;
		} else {
		
			this.newHeight = newHeight;
		}
	}
	
	private void setDefaultNw (int newWidth) {
		this.defaultNewWidth = newWidth;
	}
	
	private void setDefaultNh (int newHeight) {
		this.defaultNewHeight = newHeight;
	}
	
	public void makeImg() {
		try {
			File fi = sourceFile; 
			File fo = destinationFile; 
			
			AffineTransform transform = new AffineTransform(); 
			BufferedImage bis = ImageIO.read(fi); 
			
			int w = bis.getWidth(); 		
			int h = bis.getHeight(); 		
			double sx = (double)this.newWidth / w;
			double sy = (double)this.newHeight / h; 
			transform.setToScale(sx, sy); 
			
			AffineTransformOp ato = new AffineTransformOp(transform, null); 
			BufferedImage bid     = new BufferedImage(this.newWidth,
					newHeight, BufferedImage.TYPE_3BYTE_BGR); 
			ato.filter(bis, bid); 
			ImageIO.write(bid, JPG, fo); 
		} catch(IOException e) {
			LOG.info(e.getMessage());
		}
	}
}
